package com.demo.service.impl;

import com.demo.bean.MailParam;
import com.demo.service.MailSenderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;


@Service
public class MailServiceImpl implements MailSenderService {

    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    private SimpleMailMessage simpleMailMessage;

    @Autowired
    private ThreadPoolTaskExecutor poolTaskExecutor;


    /**
     * 发送邮件实现方法
     * @param mailParam from 发送人，to收件人,subject 主题,content 邮件内容
     */
    @Override
    public void mailSend(final MailParam mailParam) {
        //填充模板
        poolTaskExecutor.execute(new Runnable() {
            @Override
            public void run() {
                simpleMailMessage.setFrom(simpleMailMessage.getFrom());
                simpleMailMessage.setTo(mailParam.getTo());
                simpleMailMessage.setSubject(mailParam.getSubject());
                simpleMailMessage.setText(mailParam.getContent());
                javaMailSender.send(simpleMailMessage);
            }
        });

    }

    @Override
    public void sendEmailWithAttachment(MailParam mailParam)  {
        try {
            MimeMessage message = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);//构造消息helper，第二个参数表明这个消息是multipart类型的
            helper.setFrom(simpleMailMessage.getFrom());
            helper.setTo(mailParam.getTo());
            helper.setSubject(mailParam.getSubject());
            helper.setText(mailParam.getContent());
            //使用Spring的FileSystemResource来加载fox.png
            FileSystemResource image = new FileSystemResource("D:\\1.png");
            System.out.println(image.exists());
            //添加附加，第一个参数为添加到Email中附件的名称，第二个人参数是图片资源
            helper.addAttachment("附件图片.png", image);
            javaMailSender.send(message);
        }catch (Exception e){
            throw new RuntimeException("邮件发送失败");
        }

    }

}
